/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package desk;

import com.itextpdf.text.DocumentException;
import ejb.ProductManager;
import ejb.ReportManager;
import ejb.RequestManager;
import ejb.Security;
import helpClasses.ReportProperties;
import hibernate.Product;
import hibernate.ProductCategory;
import hibernate.Request;
import hibernate.RequestStatus;
import hibernate.User;
import hibernate.UserRole;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import java.util.Comparator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.*;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

/**
 * Бин отображения списков запросов и выполнения операций над ними
 * @author AGolubinskyy
 */
@ManagedBean(name = "rlb")
@ViewScoped
public class RquestListerBean  implements Serializable{

    @ManagedProperty(value = "#{webClientController}")
    private WebClientController clientController;
    private Security security = null;
    private ReportManager reportManager = null;
    private RequestManager requestmanager = null;
    private ProductManager productManager = null;
    private int userToShow = -1,
            managerToShow = -1,
            categoryToShow = -1,
            productToShow = -1,
            statusToShow = RequestStatus.GET_IN_PROGRESS_STATUS().getId();
    private String comment;

    public List<SelectItem> getUsers() {
        return getUsers(null);
    }

    public List<SelectItem> getManagers() {
        return getUsers(UserRole.GET_MANAGER_ROLE());
    }
    
    private List<SelectItem> getUsers(UserRole role){
        List<SelectItem> items = new ArrayList<SelectItem>();
        items.add(new SelectItem(-1, "All users"));
        List<User> users;
        if (role == null){
            users = security.getAllUsers();
        } else {
            users = security.getUsersByRole(role);      
        }
        if (users != null) {
            for (User u : users) {
                items.add(new SelectItem(u.getId(), u.getFirstName() + " " + u.getLastName()));
            }
        }
        return items;
    }

    public List<SelectItem> getCategories() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        items.add(new SelectItem(-1, "All Categories"));
        List<ProductCategory> cats = productManager.getAllCategories();
        if (cats != null) {
            for (ProductCategory pc : cats) {
                items.add(new SelectItem(pc.getId(), pc.getDescription()));
            }
        }
        return items;
    }

    public List<SelectItem> getProducts() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        items.add(new SelectItem(-1, "All products"));
        List<Product> prods = productManager.getAllProducts();
        if (prods != null) {
            if (categoryToShow == -1) {
                for (Product p : prods) {
                    items.add(new SelectItem(p.getId(), p.getDescription()));
                }
            } else {
                for (Product p : productManager.getAllProductsInCategory(categoryToShow)) {
                    items.add(new SelectItem(p.getId(), p.getDescription()));
                }
            }
        }
        return items;
    }

    public List<SelectItem> getStatuses() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        items.add(new SelectItem(-1, "All statuses"));
        for (RequestStatus rs : requestmanager.getAllRequestStatuses()){
            items.add(new SelectItem(rs.getId(), rs.getDescription()));
        }
        return items;
    }

    public List<Request> getRequests() {
        ReportProperties rp = new ReportProperties();

        if (userToShow != -1){
            rp.setUser(security.getUserByID(userToShow));
        }

        
        if (productToShow != -1){
            rp.setProduct(productManager.getProductByID(productToShow));
        } else {
            if (categoryToShow != -1){
                rp.setProducts(productManager.getAllProductsInCategory(categoryToShow));
            }      
        }
        if (statusToShow != -1){
            // get status by id
            rp.setStatus(requestmanager.getRequestStatusByID(statusToShow));
        }
        if (managerToShow != -1){
            rp.setManager(security.getUserByID(managerToShow));
        }
        List<Request> requests = reportManager.getRequests(rp);
        Collections.sort(requests, new Comparator<Request>(){

            @Override
            public int compare(Request o1, Request o2) {
                return o1.getInDate().compareTo(o2.getInDate()) * -1;
            }
        
    });
        return requests;
        
        //return reportManager.getAllRequests();
    }

    /**
     * Выставляет запросу статус Completed 
     * @param r
     */
    public void complete(Request r) throws Exception {
        r.setStatus(RequestStatus.GET_COMPLETED_STATUS());
        r.setComment(comment);
        requestmanager.update(r); //
    }

    /**
     * Выставляет запросу статус Rejected 
     * @param r
     */
    public void reject(Request r) throws Exception {
        r.setStatus(RequestStatus.GET_REJECTED_STATUS());
        r.setComment(comment);
        requestmanager.update(r);
    }

    /**
     * Выводит файл в соответствии с заданными настройками фильтрации в поток
     */
    public void exportPdfFile() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "inline=filename=report.pdf");

        try {           
            PdfCreator p = new PdfCreator("template.properties");
            p.createPdfSaveToStream(getRequests(), response.getOutputStream(), false);
            response.getOutputStream().flush();
            response.getOutputStream().close();
            context.responseComplete();
        } catch (DocumentException ex) {
            Logger.getLogger(RquestListerBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException e) {
        }
    }

    public int getUserToShow() {
        return userToShow;
    }

    public void setUserToShow(int userToShow) {
        this.userToShow = userToShow;
    }

    public int getManagerToShow() {
        return managerToShow;
    }

    public void setManagerToShow(int managerToShow) {
        this.managerToShow = managerToShow;
    }

    public int getCategoryToShow() {
        return categoryToShow;
    }

    public void setCategoryToShow(int categoryToShow) {
        this.categoryToShow = categoryToShow;
    }

    public int getProductToShow() {
        return productToShow;
    }

    public void setProductToShow(int productToShow) {
        this.productToShow = productToShow;
    }

    public String getUserRole() {
        return security.getCurrentUser().getRole().getRoleName().toLowerCase();
    }

    public int getStatusToShow() {
        return statusToShow;
    }

    public void setStatusToShow(int statusToShow) {
        this.statusToShow = statusToShow;
    }

    public void setClientController(WebClientController clientController) {
        this.clientController = clientController;
        security = clientController.getServerManager().getSecurity();
        reportManager = clientController.getServerManager().getReportManager();
        productManager = clientController.getServerManager().getProductManager();
        requestmanager = clientController.getServerManager().getRequestManager();
    }

    public String getComment() {
        return "";
    }

    public void setComment(String comment) {
        this.comment = comment;
    }
}
